import api from '@/store/api';
import i18n from '@/i18n';
const { t } = i18n.global as any;

export const usePowerPolicyStore = defineStore('powerPolicy', () => {
  const powerRestoreCurrentPolicy = ref(null);
  const powerRestorePolicies = ref([] as any[]);

  const setPowerRestoreCurrentPolicy = (currentPolicy: any) =>
    (powerRestoreCurrentPolicy.value = currentPolicy);
  const setPowerRestorePolicies = (Policies: any) =>
    (powerRestorePolicies.value = Policies);

  const getPowerRestorePolicies = async () => {
    return await api
      .get('/redfish/v1/JsonSchemas/ComputerSystem/ComputerSystem.json')
      .then(
        ({
          data: {
            definitions: { PowerRestorePolicyTypes = {} },
          },
        }) => {
          const powerPoliciesData = PowerRestorePolicyTypes.enum.map(
            (powerState: string | number) => {
              const desc = `${t(
                `pagePowerRestorePolicy.policies.${powerState}`,
              )} - ${PowerRestorePolicyTypes.enumDescriptions[powerState]}`;
              return {
                state: powerState,
                desc,
              };
            },
          );
          setPowerRestorePolicies(powerPoliciesData);
        },
      );
  };
  const getPowerRestoreCurrentPolicy = async () => {
    return await api
      .get('/redfish/v1/Systems/system')
      .then(({ data: { PowerRestorePolicy } }) => {
        setPowerRestoreCurrentPolicy(PowerRestorePolicy);
      })
      .catch((error) => console.log(error));
  };
  const setPowerRestorePolicy = async (powerPolicy: any) => {
    const data = { PowerRestorePolicy: powerPolicy };

    return await api
      .patch('/redfish/v1/Systems/system', data)
      .then(() => setPowerRestoreCurrentPolicy(data.PowerRestorePolicy))
      .then(() => t('pagePowerRestorePolicy.toast.successSaveSettings'))
      .catch((error) => {
        console.log(error);
        throw new Error(
          t('pagePowerRestorePolicy.toast.errorSaveSettings') as string,
        );
      });
  };

  return {
    powerRestoreCurrentPolicy,
    powerRestorePolicies,
    setPowerRestoreCurrentPolicy,
    setPowerRestorePolicies,
    getPowerRestorePolicies,
    getPowerRestoreCurrentPolicy,
    setPowerRestorePolicy,
  };
});
